package com.mobilesales.android.infrastructure;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Gallery;

import com.mobilesales.android.R;
import com.mobilesales.android.adapters.ProductImageAdapter;
import com.mobilesales.android.model.products.ProductImage;
import com.mobilesales.android.util.MessageBox;

public class DownloadImagesTask extends AsyncTask<Void, Void, List<Bitmap>> {

	private Context context;
	private List<ProductImage> images;
	private Gallery gallery;

	public DownloadImagesTask(Context context,List<ProductImage> images,
			Gallery gallery) {
		this.context = context;
		this.images = images;
		this.gallery = gallery;
	}

	@Override
	protected List<Bitmap> doInBackground(Void... arg0) {
		List<Bitmap> result = null;
		if (images != null) {
			result = new ArrayList<Bitmap>();
			for (ProductImage img : images) {
				InputStream is = null;
				try {
					URL url = new URL(img.Path);
					HttpURLConnection con = (HttpURLConnection) url
							.openConnection();
					is = con.getInputStream();
					Bitmap bmp = BitmapFactory.decodeStream(is);
					if (null != bmp) {
						result.add(bmp);
					}
					is.close();
				} catch (Exception e) {
					Log.e("DownloadImagesTask", e.getMessage(), e);
				} finally {
					if (is != null) {
						try {
							is.close();
						} catch (IOException e) {
							Log.e("Close stream", e.getMessage(), e);
						}
					}
				}
			}
			return result;
		}
		return result;
	}

	@Override
	protected void onPostExecute(List<Bitmap> result) {
		boolean success = true;
		if (result == null)
			success = false;
		else if (images != null && result.size() != images.size())
			success = false;

		if (!success) {
			MessageBox.show(context,
					context.getString(R.string.ErrorDownloadProductImages));
		}
		else {
			if (gallery!=null) {
				ProductImageAdapter adapter = new ProductImageAdapter(context, result);
				gallery.setAdapter(adapter);
			}
		}
	}
}
